package com.qiyou.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.qiyou.dao.IBlogDao;
import com.qiyou.dao.factory.DaoFactory;
import com.qiyou.entity.Blog;
import com.qiyou.util.LogUtil;

/**
 * 全部博客信息
 * 
 * @author 杨强
 */
@WebServlet("/BlogListService")
public class BlogListService extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static final Logger log = LogUtil.getLogger(BlogListService.class);

    public BlogListService()
    {
        super();
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");

        String sortType = request.getParameter("sortType");
        if (sortType == null || sortType.isEmpty())
        {
            sortType = "blogDate";
        }
        String sql = "order by " + sortType + " desc";

        IBlogDao dao = DaoFactory.getBlogDao();
        List<Blog> blogs = null;
        try
        {
            blogs = dao.getBlogs(new Object[] { sql });
        }
        catch (SQLException e)
        {
            log.error(e);
        }
        JSONArray questionjson = new JSONArray();
        if (blogs != null && !blogs.isEmpty())
        {
            for (Blog blog : blogs)
            {
                questionjson.put(new JSONObject(blog));
            }
        }
        String msg = questionjson.toString();
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();

        log.info("用户:" + request.getRemoteAddr() + ",访问了博客列表信息:" + msg);
    }

}
